<!-- 封装echarts通用组件 -->
<template>
  <div ref="chartsRef" :style="{ height: height, width: width }" :option="option"></div>
</template>

<script setup lang="ts">
import { ECharts, EchartsOption, init } from 'echarts'
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
//定义一个描述组件的props接口
interface Props {
  option: EchartsOption
  width?: string
  height?: string
}

const props = withDefaults(defineProps<Props>(), {
  width: '100%',
  height: '100%',
  option: () => ({})
})

const chartsRef = ref<HTMLElement | null>(null)
let myChart: ECharts

let timer: string | number | NodeJS.Timeout | undefined

// 初始化echarts
const initChart = (): void => {
  if (myChart !== undefined && myChart !== null) {
    myChart.dispose()
  }
  myChart = init(chartsRef.value as HTMLDivElement)

  // 通过option配置项,渲染echarts
  myChart?.setOption(props.option, true)
}

// 重新渲染echarts
const resizeChart = (): void => {
  (timer) =>
    setTimeout(() => {
      myChart?.resize()
    }, 500)
};

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (myChart !== undefined && myChart !== null) {
    myChart.dispose()
  }
  clearTimeout(timer);
  timer = 0;
})

watch(
  () => props.option,
  () => {
    initChart()
  },
  { deep: true }
)
//添加树图点击事件
//
</script>
